package com.blb.netty.encode;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

/**
 * Netty客户端
 */
public class MyNettyClient {

    /**
     * 发消息给服务器端
     */
    public void sendMessage(String ip,int port,Long message){
        //创建工作线程组
        NioEventLoopGroup workGroup = new NioEventLoopGroup(1);
        //创建启动对象
        Bootstrap bootstrap = new Bootstrap();
        //配置启动对象
        bootstrap.group(workGroup)
                .channel(NioSocketChannel.class) //通道类型
                .handler(new ChannelInitializer<SocketChannel>() { //处理器
                    @Override
                    protected void initChannel(SocketChannel socketChannel) throws Exception {
                        socketChannel.pipeline()
                                .addLast(new ByteToLongDecoder())
                                .addLast(new LongToByteEncoder())
                                .addLast(new NettyClientHandler()); //自定义处理器
                    }
                });
        //连接服务器
        try {
            ChannelFuture sync = bootstrap.connect(ip, port).sync();
            //发消息给服务器端
            sync.channel().writeAndFlush(message);
            sync.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    /**
     * 客户端处理器
     */
    static class NettyClientHandler extends SimpleChannelInboundHandler<Long>{

        @Override
        protected void channelRead0(ChannelHandlerContext channelHandlerContext, Long s) throws Exception {
            System.out.println("客户端收到消息：" + s);
        }
    }

    public static void main(String[] args) {
        new MyNettyClient().sendMessage("192.168.114.22",6666,99999999999L);
    }
}
